#!/bin/bash
# 安全的测试执行器 - 解决GC卡住问题

cd "$(dirname "$0")/.."

echo "🔧 Yao Framework 安全测试执行器"
echo "=============================="

# 加载GC优化配置
if [ -f .env.gc ]; then
    source .env.gc
    echo "✅ 已加载GC优化配置"
else
    echo "⚠️ 未找到GC配置文件，使用默认参数"
    export CANGJIE_GC_HEAP_SIZE=256m
    export CANGJIE_GC_MAX_HEAP_SIZE=512m
    export CANGJIE_GC_STW_TIMEOUT=15000
fi

# 显示当前配置
echo "📊 当前GC配置:"
echo "  堆大小: ${CANGJIE_GC_HEAP_SIZE:-默认}"
echo "  最大堆: ${CANGJIE_GC_MAX_HEAP_SIZE:-默认}"
echo "  STW超时: ${CANGJIE_GC_STW_TIMEOUT:-默认}ms"

# 构建项目
echo ""
echo "🔨 构建项目..."
if ! cjpm build; then
    echo "❌ 构建失败"
    exit 1
fi

# 根据参数选择测试策略
case "${1:-minimal}" in
    "minimal")
        echo ""
        echo "🧪 运行最小化测试..."
        echo "这是最安全的测试，用于验证基础功能"
        cjpm test --filter MinimalDiagnosticTest
        ;;
    "memory")
        echo ""
        echo "🧪 运行内存测试..."
        cjpm test --filter MemoryDiagnosticTest
        ;;
    "gc")
        echo ""
        echo "🧪 运行GC测试..."
        cjpm test --filter GCFriendlyTest
        ;;
    "batch")
        echo ""
        echo "🧪 运行分批测试..."
        echo "这是推荐的测试策略，避免GC问题"
        
        echo "1/3 运行最小化测试..."
        cjpm test --filter MinimalDiagnosticTest
        
        echo "2/3 运行内存测试..."
        cjpm test --filter MemoryDiagnosticTest
        
        echo "3/3 运行GC测试..."
        cjpm test --filter GCFriendlyTest
        
        echo "✅ 分批测试完成"
        ;;
    "all")
        echo ""
        echo "🧪 运行完整测试..."
        echo "⚠️ 注意：如果卡住，请按Ctrl+C终止"
        cjpm test
        ;;
    *)
        echo "用法: $0 [minimal|memory|gc|batch|all]"
        echo ""
        echo "测试选项:"
        echo "  minimal - 最小化测试（推荐，最安全）"
        echo "  memory  - 内存测试"
        echo "  gc      - GC测试"
        echo "  batch   - 分批测试（推荐，避免GC问题）"
        echo "  all     - 完整测试（可能卡住）"
        echo ""
        echo "示例:"
        echo "  $0 minimal  # 快速验证"
        echo "  $0 batch    # 完整但安全的测试"
        ;;
esac
